import json

with open('pop.csv','r') as fr:
    all = fr.read().split('\n')
with open('foreign.json','r') as fr:
    all2 = json.loads(fr.read())

countryL = []
for k, v in all2.items():
    countryL.append(v[0][2])

included = {}
for c in all:
    items = c.split('\t')
    if items[1] in countryL:
        included[items[1]] = items[2]
ct = 0
for k, v in all2.items():
    populationIncluded = False
    for k2, v2 in included.items():
        if v[0][2] == 'China':
            v[0].append({'pop': int(included['China'].replace(',', ''))
                                + int(included['Taiwan'].replace(',', ''))
                                + int(included['Hong Kong'].replace(',', ''))
                                + int(included['Macao'].replace(',', ''))})
        elif v[0][2] == k2:
            ct += 1
            v[0].append({'pop':int(v2.replace(',',''))})
            populationIncluded = True
            break
    if populationIncluded == False:
        v[0].append({'pop':-1})

for k, v in all2.items():
    print(k, v)

with open('foreign_c_pop.json','w') as fw:
    fw.write(json.dumps(all2, separators=(',',':'), ensure_ascii = False))